class HttpRequest {
    constructor() {
        this.baseURL = `/api`;
        this.timeout = 10000;
    }

    // 鑾峰彇鐢ㄦ埛淇℃伅
    getUserInfo() {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        if (!userInfo) {
            alert('Login expired, please login again');
            window.location.href = '/login.html?redirect=' + window.location.href;
        }
        return userInfo;
    }

    // 璁剧疆鐢ㄦ埛淇℃伅
    setUserInfo(userInfo) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
    }

    // 鑾峰彇瀛樺偍鐨則oken
    getToken() {
        return localStorage.getItem('token');
    }

    // 璁剧疆token
    setToken(token) {
        localStorage.setItem('token', token);
    }

    // 绉婚櫎token
    removeToken() {
        localStorage.removeItem('token');
    }

    // 澶勭悊璇锋眰澶�
    getHeaders(contentType = 'application/json') {
        const headers = {
            'Content-Type': contentType
        };
        const token = this.getToken();
        if (token) {
            headers['Authorization'] = `${token}`;
        }
        return headers;
    }

    // 澶勭悊鍝嶅簲
    handleResponse(response) {
        return response.json().then(data => {
            if (data.code === 200) {
                return data.data;
            } else {
                console.log(data);
                // 澶勭悊鐗瑰畾閿欒鐮�
                switch (data.code) {
                    case 403:
                        this.removeToken();
                        // 浣跨敤閲嶅畾鍚�
                        window.location.href = '/login.html?redirect=' + window.location.href;
                        throw new Error('Login expired, please login again');
                    default:
                        throw new Error(data.message || '璇锋眰澶辫触');
                }
            }
        });
    }

    // GET璇锋眰
    async get(url, params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const fullUrl = `${this.baseURL}${url}${queryString ? '?' + queryString : ''}`;
        
        try {
            const response = await fetch(fullUrl, {
                method: 'GET',
                headers: this.getHeaders(),
                credentials: 'include'
            });
            return this.handleResponse(response);
        } catch (error) {
            console.error('Request failed:', error);
            throw error;
        }
    }

    // POST璇锋眰
    async post(url, data) {
        try {
            const options = {
                method: 'POST',
                headers: this.getHeaders(),
                credentials: 'include'
            };

            // 濡傛灉鏄� FormData锛屼笉璁剧疆 Content-Type锛岃娴忚鍣ㄨ嚜鍔ㄥ鐞�
            if (!(data instanceof FormData)) {
                options.headers['Content-Type'] = 'application/json';
                options.body = JSON.stringify(data);
            } else {
                delete options.headers['Content-Type'];
                options.body = data;
            }

            const response = await fetch(`${this.baseURL}${url}`, options);
            return this.handleResponse(response);
        } catch (error) {
            console.error('Request failed:', error);
            throw error;
        }
    }

    // PUT璇锋眰
    async put(url, data) {
        try {
            const options = {
                method: 'PUT',
                headers: this.getHeaders(),
                credentials: 'include'
            };

            // 濡傛灉鏄� FormData锛屼笉璁剧疆 Content-Type锛岃娴忚鍣ㄨ嚜鍔ㄥ锟斤拷锟�
            if (!(data instanceof FormData)) {
                options.headers['Content-Type'] = 'application/json';
                options.body = JSON.stringify(data);
            } else {
                delete options.headers['Content-Type'];
                options.body = data;
            }

            const response = await fetch(`${this.baseURL}${url}`, options);
            return this.handleResponse(response);
        } catch (error) {
            console.error('Request failed:', error);
            throw error;
        }
    }

    // DELETE璇锋眰
    async delete(url) {
        try {
            const response = await fetch(`${this.baseURL}${url}`, {
                method: 'DELETE',
                headers: this.getHeaders(),
                credentials: 'include'
            });
            return this.handleResponse(response);
        } catch (error) {
            console.error('Request failed:', error);
            throw error;
        }
    }

    // 添加内容处理工具函数, 防止XSS攻击
    escapeHtml(str) {
        if (!str) return '';
        return str
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    // 格式化内容
    formatContent(content) {
        return this.escapeHtml(content)
            .replace(/\n/g, '<br>')
            .replace(/\s{2,}/g, space => ' ' + '&nbsp;'.repeat(space.length - 1));
    }
}

const http = new HttpRequest();
export default http;     // 导出实例 